<template>
  <div class="lock-pc">
    <el-dialog
        :title="type?'Please set your payment pin':'Input your payment pin'"
        :visible.sync="passwordVisible"
        width="30%"
        :modal="false"
        :close-on-click-modal="false"
        :before-close="handleClose">
      <el-form ref="form" :model="form" :rules="rules" label-width="0px">
        <el-form-item prop="password">
          <el-input v-model="form.password" type="password" maxLength="6" placeholder="payment pin" onkeyup="this.value = this.value.replace(/[^\d.]/g,'');"></el-input>
        </el-form-item>
      </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleClose">Cancel</el-button>
          <el-button type="primary" @click="handleConfirm">OK</el-button>
        </span>
    </el-dialog>

  </div>
</template>

<script>

import {checkPayCode, setPayCode, validatePayCode} from "@/api/shopMall";
import {mapState} from "vuex";

export default {
  name: "lockPc",
  props:{
    passwordVisible:{
      type:Boolean
    },
  },
  data(){
    return{
      form:{
        password:'',
      },
      type:true,
      rules: {
        password: [
          {required: true,min:6, message: 'Only 6 numbers accepted as your payment password', trigger: 'change'},
        ],
      }
    }
  },
  computed: {
    ...mapState({comData: state => state.comData.comData})
  },

  created() {
    checkPayCode({memberId: this.comData.memberId}).then(res => {
      this.type = res.data === 202;
    })
  },

  methods:{
    handleClose(){
      this.$emit('handleClose')
    },

    handleConfirm(){
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if(this.type){
            setPayCode({ memberId: this.comData.memberId,
              pwd: this.form.password,authCode:this.comData.authCode})
                .then(res => {
                  if(res){
                    this.$emit('handlePayment')
                  }
                })
          }else {
            validatePayCode({memberId: this.comData.memberId, pwd: this.form.password,authCode:this.comData.authCode})
                .then(res => {
                  if(res){
                    this.$emit('handlePayment')
                  }
                })
          }
        } else {
          return false;
        }
      });
    }
  }
}
</script>

<style scoped>

</style>
